import React, { useState, useEffect } from 'react';
import { IssueType} from '@/types/aiCorrector';
import type { AICorrectionIssue } from '@/types/aiCorrector';
import { ComplianceType, RiskLevel, ComplianceStatus } from '@/types/work';
import type { ComplianceItem } from '@/types/work';
import { useAiCorrectorStore } from '@/stores/useAiCorrectorStore';
import { useComplianceStore } from '@/stores/useComplianceStore';

interface InlineEditorProps {
  issue: AICorrectionIssue;
  complianceItem: ComplianceItem;
  onSave: (updatedData: Partial<ComplianceItem>) => void;
}

const InlineEditor: React.FC<InlineEditorProps> = ({
  issue,
  complianceItem,
  onSave
}) => {
  // 使用上下文获取所需的方法
  const { cancelEdit, getModifiedItem } = useAiCorrectorStore();
  const { items } = useComplianceStore();
  
  // 获取最新的检查项数据
  const latestItem = items.find(item => item.id === issue.itemId);
  
  // 获取已修改但未应用的数据
  const modifiedItem = getModifiedItem(issue.id);
  
  // 优先使用修改过的数据，然后是最新的数据，最后是传入的数据
  const currentItem = modifiedItem || latestItem || complianceItem;
  
  // 根据问题类型初始化编辑状态
  const [editValue, setEditValue] = useState<string | RiskLevel | ComplianceStatus>('');
  
  useEffect(() => {
    // 根据问题类型设置初始值
    switch (issue.type) {
      case IssueType.TYPO:
      case IssueType.SEMANTIC:
        setEditValue(currentItem.inspector || ''); // 错别字和语义混乱检查针对检查人员描述
        break;
      case IssueType.RISK_LEVEL:
        setEditValue(currentItem.risk_level || RiskLevel.MEDIUM);
        break;
      case IssueType.COMPLIANCE_STATUS:
        setEditValue(currentItem.compliance_status || ComplianceStatus.PARTIALLY_COMPLIANT);
        break;
    }
  }, [issue.id, issue.type, currentItem.inspector, currentItem.risk_level, currentItem.compliance_status]);

  // 处理保存操作
  const handleSave = () => {
    const updatedData: Partial<ComplianceItem> = {
      updated_at: new Date().toISOString()
    };

    // 根据问题类型更新不同的字段
    switch (issue.type) {
      case IssueType.TYPO:
      case IssueType.SEMANTIC:
        updatedData.inspector = editValue as string; // 更新检查人员描述属性
        break;
      case IssueType.RISK_LEVEL:
        updatedData.risk_level = editValue as RiskLevel;
        break;
      case IssueType.COMPLIANCE_STATUS:
        updatedData.compliance_status = editValue as ComplianceStatus;
        break;
    }

    onSave(updatedData);
  };

  // 处理键盘事件
  const handleKeyDown = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter' && e.ctrlKey) {
      handleSave();
    } else if (e.key === 'Escape') {
      cancelEdit();
    }
  };

  // 根据问题类型渲染不同的编辑组件
  const renderEditor = () => {
    switch (issue.type) {
      case IssueType.TYPO:
      case IssueType.SEMANTIC:
        return (
          <textarea
            className="w-full p-3 border border-input rounded-md focus:outline-none focus:ring-2 focus:ring-ring bg-muted"
            value={editValue as string}
            onChange={(e) => setEditValue(e.target.value)}
            onKeyDown={handleKeyDown}
            rows={4}
            placeholder="输入检查人员描述"
            autoFocus
          />
        );
      
      case IssueType.RISK_LEVEL:
        if (complianceItem.compliance_type !== ComplianceType.RISK) {
          return <div className="text-destructive">此项不是风险项，无法编辑风险等级</div>;
        }
        return (
          <select
            className="w-full p-3 border border-input rounded-md focus:outline-none focus:ring-2 focus:ring-ring bg-muted"
            value={editValue as string}
            onChange={(e) => setEditValue(e.target.value as RiskLevel)}
            onKeyDown={handleKeyDown}
            autoFocus
          >
            <option value={RiskLevel.HIGH}>高风险</option>
            <option value={RiskLevel.MEDIUM}>中风险</option>
            <option value={RiskLevel.LOW}>低风险</option>
            <option value={RiskLevel.NOT_APPLICABLE}>不适用</option>
          </select>
        );
      
      case IssueType.COMPLIANCE_STATUS:
        return (
          <select
            className="w-full p-3 border border-input rounded-md focus:outline-none focus:ring-2 focus:ring-ring bg-muted"
            value={editValue as string}
            onChange={(e) => setEditValue(e.target.value as ComplianceStatus)}
            onKeyDown={handleKeyDown}
            autoFocus
          >
            <option value={ComplianceStatus.FULLY_COMPLIANT}>完全满足</option>
            <option value={ComplianceStatus.PARTIALLY_COMPLIANT}>基本满足</option>
            <option value={ComplianceStatus.NON_COMPLIANT}>不满足</option>
            <option value={ComplianceStatus.NOT_APPLICABLE}>不适用</option>
          </select>
        );
      
      default:
        return <div>不支持编辑此类型的问题</div>;
    }
  };

  return (
    <div className="bg-muted p-4 rounded-md mt-4">
      <h4 className="text-sm font-medium text-foreground mb-2">
        修改{issue.type === IssueType.TYPO || issue.type === IssueType.SEMANTIC 
          ? '检查人员描述' 
          : issue.type === IssueType.RISK_LEVEL 
            ? '风险等级' 
            : '合规状态'}
      </h4>
      
      {renderEditor()}
      
      <div className="flex justify-end gap-2 mt-3">
        <button
          onClick={cancelEdit}
          className="px-4 py-2 text-sm border border-input rounded-md hover:bg-muted focus:outline-none focus:ring-2 focus:ring-ring"
        >
          取消
        </button>
        <button
          onClick={handleSave}
          className="px-4 py-2 text-sm bg-primary text-primary-foreground rounded-md  focus:outline-none focus:ring-2 focus:ring-ring"
        >
          保存
        </button>
      </div>
      
      <div className="text-xs text-muted-foreground mt-2">
        提示：按 Ctrl+Enter 保存，按 Esc 取消
      </div>
    </div>
  );
};

export default InlineEditor;
